package gen.tools.modUnit;

import gen.tools.Widgets;
import gen.tools.structures.ModNodeAdv;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class ApplyModDependency extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public ApplyModDependency() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		final Widgets wid = new Widgets();
		request.setCharacterEncoding( wid.UIcodeSet );
		response.setCharacterEncoding( wid.UIcodeSet );
		response.setContentType("application/text");
		
		final String subsysId = request.getParameter("subsysId");		//子系統ID
		final String empId = request.getParameter("empId");				//員工ID
		
		//相依性的申請集合
		final ArrayList<ModNodeAdv> ArrModNode = new Gson().fromJson(request.getParameter("modNodeAdvJSON"), new TypeToken<List<ModNodeAdv>>(){}.getType());
		
		String strSQL;
		String res ="Done";
		
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		try {
			conn = wid.getConn();
			conn.setAutoCommit(false);	//為取得序號，先將提交關閉
			
			/****建立LOG，第一步就開始記錄程式的執行****/
			strSQL="INSERT INTO changelog (changeLogId,changeTypeId,creatorId,bDate) VALUES (null,1,?,?)";
			ps = conn.prepareStatement(strSQL);
			ps.setString(1, empId);
			ps.setTimestamp(2, wid.cDT());
			ps.execute();
			strSQL="SELECT MAX(changeLogId) FROM changelog";
			ps = conn.prepareStatement(strSQL);
			rs = ps.executeQuery();
			rs.next();
			final int applyModDep = rs.getInt(1);
			
			
			/****創建變更申請****/
			strSQL = "INSERT INTO cramain (craId,subsysId,craStatusId,craTypeId,creatorId,cDT) VALUES (null,?,?,?,?,?)";
			ps = conn.prepareStatement(strSQL);
			ps.setString(1, subsysId);
			ps.setInt(2, 10);	//開發人員申請模組建置相依順序定義待審
			ps.setInt(3, 4);	//4 表為設定相依性
			ps.setString(4, empId);
			ps.setTimestamp(5, wid.cDT());
			ps.execute();
			
			//保存新產生的變更申請序號，等等創建細項要用
			strSQL="SELECT MAX(craId) FROM cramain";
			ps = conn.prepareStatement(strSQL);
			rs = ps.executeQuery();
			rs.next();
			final int craId = rs.getInt(1);		//變更申請序號ID
			
			/****創建變更申請細項****/
			for (int i=0; i< ArrModNode.size();i++) {
				strSQL = "INSERT INTO cradetail (craId,craDetId,modUnitId,isOpen) VALUES (?,?,?,'f')";
				ps = conn.prepareStatement(strSQL);
				ps.setInt(1, craId);
				ps.setInt(2, (i+1));
				ps.setString(3, ArrModNode.get(i).getCurrentNode());
				ps.execute();
				
				/****創建 相依性設定****/
				for(int j=0; j< ArrModNode.get(i).getDownStreamNode().size(); j++) {
					strSQL = "INSERT INTO cradependency (craId,craDetId,craDepenId,modId) VALUES (?,?,?,?)";
					ps = conn.prepareStatement(strSQL);
					ps.setInt(1, craId);
					ps.setInt(2, (i+1));
					ps.setInt(3, (j+1));
					ps.setString(4, ArrModNode.get(i).getDownStreamNode().get(j));
					ps.execute();
				}
			}
			
			
			/****將這次模組的新增，送至主管待審****/
			/****建立LOG，產生另一筆記錄動作****/
			strSQL="INSERT INTO changelog (changeLogId,changeTypeId,creatorId,bDate) VALUES (null,16,?,?)";
			ps = conn.prepareStatement(strSQL);
			ps.setString(1, empId);
			ps.setTimestamp(2, wid.cDT());
			ps.execute();
			
			/****產生待辦事項****/
			strSQL="INSERT INTO todolist (subsysId,dataType,masterId,roleId,cDT,creatorId) VALUES (?,?,?,?,?,?)";
			ps = conn.prepareStatement(strSQL);
			ps.setString(1, subsysId);
			ps.setInt(2, 6);				//主檔類型，6表示這個ID是申請定義模組相依性，共用變更申請主檔
			ps.setString(3, String.valueOf(craId) );			//主檔ID
			ps.setInt(4, 4);				//角色ID
			ps.setTimestamp(5, wid.cDT());
			ps.setString(6, empId);
			ps.execute();
			
			
			/****完成這次的異動****/
			strSQL = "UPDATE changelog SET eDate=? WHERE changeLogId=?";
			ps = conn.prepareStatement(strSQL);
			ps.setTimestamp(1, wid.cDT());
			ps.setInt(2, applyModDep);
			ps.execute();
			conn.commit();
		
		} catch(Exception e) {
			res = wid.errProcess(e);
			wid.errLog(e);
		} finally {
			try {
				if ( rs !=null ) {rs.close();}
				if ( ps !=null ) {ps.close();}
				if ( conn !=null ) {conn.close();}	
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		response.getWriter().write( res );
		
		
	}

}
